package currentment.printOrder;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintInOrder_Synchronized {
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private int index = 0;

    public void print(int target) {
            lock.lock();
            try {
                while (index % 3 != target) {
                    condition.await();
                }
                System.out.println(Thread.currentThread().getName() + ":" + index++);
                condition.signalAll();

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }
    public static void main(String[] args) {
        PrintInOrder_Synchronized print = new PrintInOrder_Synchronized();
        new Thread(() -> print.print(0), "A").start();
        new Thread(() -> print.print(1), "B").start();
        new Thread(() -> print.print(2), "C").start();

    }
}
